import styles from './index.module.scss'
import { NavBar, Form, Input, List, Button, Toast } from 'antd-mobile'
import { useHistory, useLocation } from 'react-router-dom'
import { LoginFormType } from '@/types/data'
import { useDispatch } from 'react-redux'
import { getMobileCode, login } from '@/store/actions/login'
import { useEffect, useRef, useState } from 'react'
import { InputRef } from 'antd-mobile/es/components/input'

// 由于数据更新后,立即重新执行Login,定时器id又是不变的
// 必然需要一个贯穿始终的一个变量,能够存储正在运行的定时器,保证清除定时器无问题,useRef
export default function Login() {
  const history = useHistory()
  const dispatch = useDispatch()
  const [form] = Form.useForm()
  const mobileRef = useRef<InputRef>(null)
  const [count, setCount] = useState(0)
  let timer = useRef<number>(-1)
  const location = useLocation<{ from: string }>()

  const onFinish = async (values: LoginFormType) => {
    console.log(values)

    try {
      // async await,await只会等待成功的结果,一旦失败抛出一个错误
      await dispatch(login(values))
      Toast.show({
        icon: 'success',
        content: '登录成功',
        duration: 400,
        afterClose: () => {
          const pathname = location?.state?.from || '/home'
          // 返回首页
          history.replace(pathname)
        },
      })
    } catch (e) {
      console.log(e)
    }
  }

  const getCode = async () => {
    if (count > 0) return
    const mobile = form.getFieldValue('mobile')
    const errors = form.getFieldError('mobile')

    if (!mobile || errors.length > 0) {
      // 要么没输入手机号,要么有错误信息
      Toast.show('请输入正确的手机号')

      // 让手机号这个输入框能够获取到焦点
      mobileRef.current?.focus()
      return
    }
    // 手机号没问题,可以发送验证码
    await dispatch(getMobileCode(mobile))

    //开始倒计时
    // 1.倒计时的秒数
    // 2.开个定时器
    setCount(10)

    // 小bug,这里默认ts会识别成node中setInterval,而我们要的是window.setInterval
    timer.current = window.setInterval(() => {
      // setCount(count-1) 错误写法,拿的是定格的 0
      setCount((count) => {
        // 实时最新的state中的count
        return count - 1
      })
    }, 1000)
  }

  // 数字为0 (监视count的变化)
  useEffect(() => {
    if (count === 0) {
      clearInterval(timer.current)
    }
  }, [count])

  //跳转页面
  useEffect(() => {
    return () => {
      clearInterval(timer.current)
    }
  }, [])

  return (
    <div className={styles.root}>
      <NavBar
        onBack={() => {
          history.go(-1)
        }}
      ></NavBar>

      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form
          form={form}
          onFinish={onFinish}
          initialValues={
            {
              // mobile: '15565795721',
              // code: '246810',
            }
          }
        >
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号' },
            ]}
            className="login-item"
          >
            <Input placeholder="请输入手机号" ref={mobileRef}></Input>
          </Form.Item>
          <List.Item
            className="login-code-extra"
            extra={
              <span className="code-extra" onClick={getCode}>
                {count === 0 ? '发送验证码' : count + '秒后重试'}
              </span>
            }
          >
            <Form.Item
              name="code"
              rules={[
                { required: true, message: '请输入验证码' },
                { pattern: /^\d{6}$/, message: '请输入正确的验证码' },
              ]}
              className="login-item"
            >
              <Input placeholder="请输入验证码"></Input>
            </Form.Item>
          </List.Item>
          <Form.Item>
            <Button
              type="submit"
              color="primary"
              block
              className="login-submit"
            >
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}
